<?php
/**
 * Vendor2 MQTT 消息调试脚本
 * 模拟 MQTT 消息进行测试
 */

// 定义应用根目录
define('APP_PATH', __DIR__ . '/application/');
define('RUNTIME_PATH', __DIR__ . '/runtime/');

// 加载 ThinkPHP 框架
require __DIR__ . '/thinkphp/base.php';

use app\service\MessageParser\MessageParserFactory;
use app\service\MqttMessageHandler;
use think\Db;

// 模拟的 MQTT 消息数据
$topic = 'rziot/zftx_w06/861179035726231/result';
$messageJson = '{"c":"zidianmao","imei":"861179035726231","iccid":"89860325247554801710","ssid":"MIFI-8915","password":"1234567890","opname":"46003","dbm":"-86","simSwitch":"2","ip":"192.168.100.1","lac":"30555","version":"JZ12SC_ZIDIANMAO_20251200_V1.0.0","cell_id":"27235605","speed_downlink":0,"speed_uplink":0,"sn":"86117903572623","boot_time":"1236643","count":"8","hidden":"0"}';

// 解析 JSON
$messageData = json_decode($messageJson, true);

echo "========== Vendor2 MQTT 消息调试 ==========\n";
echo "主题: {$topic}\n";
echo "消息数据: " . json_encode($messageData, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . "\n";
echo "\n";

try {
    // 第一步：检查 IMEI 是否存在于数据库
    echo "【第一步】检查 IMEI 是否存在于数据库...\n";
    $imei = '861179035726231';
    try {
        $record = Db::name('flow_wifi_imei')->where('IMEI', $imei)->find();
        if ($record) {
            echo "✅ IMEI 存在于数据库\n";
            echo "   当前记录: " . json_encode($record, JSON_UNESCAPED_UNICODE) . "\n";
        } else {
            echo "❌ IMEI 不存在于数据库\n";
            echo "   这是问题所在！消息会被跳过\n";
            exit(1);
        }
    } catch (\Throwable $e) {
        echo "❌ 数据库查询失败: " . $e->getMessage() . "\n";
        exit(1);
    }

    echo "\n";

    // 第二步：测试协议检测
    echo "【第二步】测试协议检测...\n";
    $parser = MessageParserFactory::detect($topic, $messageData);

    if ($parser) {
        echo "✅ 检测到解析器: " . get_class($parser) . "\n";
        echo "   解析器名称: " . $parser->getName() . "\n";
        echo "   解析器版本: " . $parser->getVersion() . "\n";
    } else {
        echo "❌ 未检测到合适的解析器\n";
        exit(1);
    }

    echo "\n";
    
    // 第三步：测试消息解析
    echo "【第三步】测试消息解析...\n";
    $parsedData = $parser->parse($topic, $messageData);
    
    if ($parsedData) {
        echo "✅ 消息解析成功\n";
        echo "   解析后的数据:\n";
        foreach ($parsedData as $key => $value) {
            echo "   - {$key}: " . (is_array($value) ? json_encode($value) : $value) . "\n";
        }
    } else {
        echo "❌ 消息解析失败\n";
        exit(1);
    }
    
    echo "\n";
    
    // 第四步：测试完整的消息处理流程
    echo "【第四步】测试完整的消息处理流程...\n";
    $handler = new MqttMessageHandler();
    $result = $handler->handle($topic, $messageData);

    if ($result) {
        echo "✅ 消息处理成功\n";
        echo "   消息已添加到缓冲区\n";

        // 强制保存到数据库
        echo "\n【第五步】强制保存到数据库...\n";
        $handler->flush();
        echo "✅ 消息已保存到数据库\n";
    } else {
        echo "❌ 消息处理失败\n";
        exit(1);
    }

    // 第六步：验证数据库是否真的更新了
    echo "\n【第六步】验证数据库是否真的更新了...\n";
    try {
        $updatedRecord = Db::name('flow_wifi_imei')->where('IMEI', $imei)->find();
        if ($updatedRecord) {
            echo "✅ 数据库中找到更新后的记录\n";
            echo "   更新时间: " . ($updatedRecord['update_time'] ?? 'N/A') . "\n";
            echo "   ICCID: " . ($updatedRecord['iccid'] ?? 'N/A') . "\n";
            echo "   信号强度: " . ($updatedRecord['signal_strength'] ?? 'N/A') . "\n";
        } else {
            echo "❌ 数据库中没有找到记录\n";
        }
    } catch (\Throwable $e) {
        echo "❌ 查询失败: " . $e->getMessage() . "\n";
    }
    
    echo "\n========== 调试完成 ==========\n";
    
} catch (\Throwable $e) {
    echo "❌ 异常: " . $e->getMessage() . "\n";
    echo $e->getTraceAsString() . "\n";
    exit(1);
}

